package com.monkeyboy;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @Author Gavin
 * @date 2021.03.14 15:38
 */
public class zero_copy {
    public static void main(String[] args) throws Exception {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                write("1111111111111111111111111111111111111111111111",0);
//            }
//        }).start();
        write("123456abc",0);
    }

    public static void red(String path) {
        File file = new File(path);
        long len = file.length();
        byte[] ds = new byte[(int) len];

        try {
            MappedByteBuffer mappedByteBuffer = new RandomAccessFile(file, "rw")
                    .getChannel()
                    .map(FileChannel.MapMode.READ_WRITE, 0, len);
            for (int offset = 0; offset < len; offset++) {
                byte b = mappedByteBuffer.get();
                ds[offset] = b;
            }

            Scanner scan = new Scanner(new ByteArrayInputStream(ds), "GBK").useDelimiter(" ");
            while (scan.hasNext()) {
                System.out.print(scan.next() + " ");
            }

        } catch (IOException e) {
        }
    }

    public static void write(String content,int offset) {
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile("D://test.txt", "rw");

            FileChannel fileChannel = randomAccessFile.getChannel();

            MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 100);
            for (int i = 0; i < content.getBytes().length; i++) {
                mappedByteBuffer.put(i+offset, content.getBytes()[i]);
                System.out.println(mappedByteBuffer.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
